/**
 *  TODO fijarse que se piden muchos datos es muy paja que sea obligatorio completar
 *	todos esos campos.
 */


package ar.com.PanteraRosa.Model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


/**
 * @desc Data access object para el model de User. Se encarga de la alta baja modificacion de User en la
 * 	bd del celular.
 * @date 01/03/2012
 * @author pantera
 *
 */
public class UserDao 
{

    //Datos de la bd
    private static final String DATABASE_NAME = "panterarosa";
    private static final String DATABASE_TABLE = "user";
    private static final int DATABASE_VERSION = 2;
    
    //Campos del modelo de User
    public static final String KEY_ROWID = "UserID";
    public static final String KEY_NICK = "UserNick";
    public static final String KEY_PASSWORD = "UserPassword";
    public static final String KEY_FIRSTNAME = "UserFirstName";
    public static final String KEY_LASTNAME = "UserLastName";
    public static final String KEY_EMAIL = "UserEmail";
  

    private SQLiteDatabase mDb;
    private DatabaseHelper mDbHelper;
    private static final String TAG = "UserDao";


    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table "+ DATABASE_TABLE + "(" + 
        KEY_ROWID + " integer primary key autoincrement, " + 
        KEY_NICK + " text not null, " +
        KEY_PASSWORD + " text not null, " +
        KEY_FIRSTNAME + " text not null, " +
        KEY_LASTNAME + " text not null, " +
        KEY_EMAIL + " text not null);";

    private final Context mCtx;

    
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS user");
            onCreate(db);
        }
    }//fin DatabaseHelper

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public UserDao(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the users database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public UserDao open() throws SQLException 
    {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * cierrala conexion de la bd
     */
    public void cerrar() 
    {
        mDbHelper.close();
    }


    /**
     * Create a new user using the title and body provided. If the user is
     * successfully created return the new rowId for that user, otherwise return
     * a -1 to indicate failure.
     * 
     * @param nombre
     * @param apellido
     * @param movil
     * @param apodo
     * @return rowId or -1 if failed
     */
    public long crear(String nick, String pass, String nombre, String apellido, String mail){
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NICK, nick);
        initialValues.put(KEY_PASSWORD, pass);        
        initialValues.put(KEY_FIRSTNAME, nombre);
        initialValues.put(KEY_LASTNAME, apellido);
        initialValues.put(KEY_EMAIL, mail);
        
        long rdo = mDb.insert(DATABASE_TABLE, null, initialValues);
        
        return rdo;
    }

    /**
     * Delete the user with the given rowId
     * 
     * @param rowId id of user to delete
     * @return true if deleted, false otherwise
     */
    public boolean eliminar(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all users in the database
     * 
     * @return Cursor over all users
     */
    public Cursor cargarTodos() {
	Cursor mCursor;
        mCursor = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_FIRSTNAME,
        		KEY_LASTNAME, KEY_NICK, KEY_EMAIL}, null, null, null, null, null);        
        if (mCursor != null)
            mCursor.moveToFirst();
        
        return mCursor;
    }

    /**
     * Return a Cursor positioned at the user that matches the given rowId
     * 
     * @param rowId id of user to retrieve
     * @return Cursor positioned to matching user, if found
     * @throws SQLException if user could not be found/retrieved
     */
    public Cursor cargarPorId(long rowId) throws SQLException {

        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_FIRSTNAME, KEY_LASTNAME, KEY_NICK, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    
    
    /**
     * Return a Cursor positioned at the user that matches the given rowId
     * 
     * @param rowId id of user to retrieve
     * @return Cursor positioned to matching user, if found
     * @throws SQLException if user could not be found/retrieved
     */
    public Cursor cargarPorNick(String nick) throws SQLException {

        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_FIRSTNAME, KEY_LASTNAME, KEY_NICK, KEY_EMAIL}, KEY_NICK + "=\"" + nick + "\"", null,
                    null, null, null, null);
        if (mCursor != null)
            mCursor.moveToFirst();

        return mCursor;
    }

    /**
     * Update the user using the details provided. The user to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of user to update
     * @param rowId
     * @param nombre
     * @param apellido
     * @param movil
     * @param apodo
     * @return true if the user was successfully updated, false otherwise
     */
    public boolean actualizar(long rowId, String nombre, String apellido,String mail, String apodo){
        ContentValues args = new ContentValues();
        args.put(KEY_FIRSTNAME, nombre);
        args.put(KEY_LASTNAME, apellido);
        args.put(KEY_EMAIL, mail);
        args.put(KEY_NICK, apodo);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}
